import React, { Component } from 'react'
import {
  View,
  StyleSheet,
  ScrollView,
  Image,
  Text,
  TouchableOpacity,
  ImageBackground
} from 'react-native'
import { TextInput } from 'react-native-gesture-handler';

import NavBar from '../../../../../components/PublicHeader';
import ImagePicker from 'react-native-image-crop-picker';
import fetchWebApi from '../../../../../public/WebApi/fetchBase';
import { POST_ALBUMINFDOATA_UPLOAD, POST_APPRELNAME } from '../../../../../public/WebApi/myInfoDataInterface/userInfoListApi';
import RNFS from 'react-native-fs'
import { Constant } from '../../../../../public/js/constant';
import getStorageValue from '../../../../../utils/getStorageValue';
import Layer from '../../../../../utils/Layer';


export default class authentication extends Component {
  constructor(props) {
    super(props)
    this.state = {
      contents: '',
      typeArr: '',
      len: [],
      positive: '',
      back: '',
      cardNum: '',
      rename: '',
    }
  }

  componentDidMount = () => {

  }
  async appRelname() {
    if (this.state.cardNum != '' && this.state.rename != '' && this.state.positive != '' && this.state.back != '') {
      const res = await fetchWebApi(POST_APPRELNAME, {
        token: await getStorageValue(Constant.TOKEN),
        cardNum: this.state.cardNum,
        rename: this.state.rename,
        frontPath: this.state.positive,
        backPath: this.state.back
      }, 'POST')
      // console.log(res);
      if (res.status == 200) {
        this.props.navigation.state.params.refresh()
        this.props.navigation.goBack()// 返回上一级
        Layer.showMsg('认证成功')
      }
    } else {
      Layer.showMsg('请完成实名认证')
    }
  }

  uploadPictures(flag) {
    ImagePicker.openPicker({
      width: 300,
      height: 400,
    }).then(images => {
      // 将路径分割，取出图片类型
      this.state.len.push(images.path.split('.'))
      this.state.len.map(item => {
        this.setState({
          typeArr: item[item.length - 1]
        })
      })
      RNFS.readFile(images.path, 'base64')
        .then(content => {
          // base64 本地相册地址转换
          this.setState({
            contents: content
          })
          this.uploadDatasbase(flag)
        })
    })
      .catch(err => {
        console.log(err);
      })
  }

  async uploadDatasbase(flag) {
    const res = await fetchWebApi(POST_ALBUMINFDOATA_UPLOAD, {
      fileContent: this.state.contents,
      type: this.state.typeArr
    }, 'POST')
    // console.log('################ upload');
    // console.log(res);
    if (flag) {
      this.setState({
        positive: res.url
      })
    } else {
      this.setState({
        back: res.url
      })
    }
  }

  render() {
    return (
      <View style={styles.warper}>
        <NavBar
          navigation={this.props.navigation}
          title={"实名认证"}
        />
        <ScrollView style={styles.bodys}>
          {/* 身份证号和真实姓名 */}
          <View style={styles.list}>
            <Text style={styles.list_text}>身份证号</Text>
            <TextInput onChangeText={(value) => {
              this.setState({
                cardNum: value
              })
            }}
              onEndEditing={(vlaue) => {
                var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                if (!reg.test(vlaue.nativeEvent.text)) {
                  Layer.showMsg('身份证格式有误')
                }
              }}
              style={styles.list_input} placeholder='请输入身份证号码' />
          </View>
          <View style={styles.list}>
            <Text style={styles.list_text}>真实姓名</Text>
            <TextInput onChangeText={(value) => {
              this.setState({
                rename: value
              })
            }}
              onEndEditing={(value) => {
                var reg = /^[\u2E80-\u9FFF]+$/
                if (!reg.test(value.nativeEvent.text)) {
                  Layer.showMsg('请输入正确的姓名')
                }
              }}
              style={styles.list_input} placeholder='输入您的姓名' />
          </View>
          <View style={styles.content}>
            {/* 上传身份证照片 */}
            <Text style={styles.content_text}>上传身份证照片</Text>
            <View style={styles.content_view}>
              <TouchableOpacity onPress={() => {
                this.uploadPictures(true)
              }}>
                <ImageBackground style={styles.content_left} source={this.state.positive == '' ? require('../../../../../assets/images/authentication/left.png') : { uri: this.state.positive }}>
                  <Image style={styles.img} source={require('../../../../../assets/images/authentication/shot.png')} />
                </ImageBackground>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => {
                this.uploadPictures(false)
              }}>
                <ImageBackground style={styles.content_right} source={this.state.back == '' ? require('../../../../../assets/images/authentication/right.png') : { uri: this.state.back }}>
                  <Image style={styles.img2} source={require('../../../../../assets/images/authentication/shot.png')} />
                </ImageBackground>
              </TouchableOpacity>
            </View>
            <View>
              <Text style={styles.content_text2}>温馨提示：请确保图片内容的完整文字清晰可见，以免影响审核结果</Text>
            </View>
          </View>
          {/* 认证按钮 */}
          <TouchableOpacity onPress={() => {
            this.appRelname()
          }} style={styles.content_btn}>
            <Text style={styles.btn_text}>认证</Text>
          </TouchableOpacity>
        </ScrollView>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    height: 32,
    backgroundColor: 'transparent'
  },
  bodys: {
    padding: 15
  },
  list: {
    display: 'flex',
    flexDirection: "row",
    justifyContent: 'flex-start',
    borderBottomWidth: 1,
    borderBottomColor: '#00000014',
    marginTop: 10,
    padding: 10
  },
  list_text: {
    fontSize: 17
  },
  list_input: {
    marginTop: -10,
    marginLeft: 30
  },
  content: {
    marginTop: 30
  },
  content_text: {
    fontSize: 17
  },
  content_view: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 20
  },
  content_left: {
    width: 180,
    height: 120
  },
  content_right: {
    width: 180,
    height: 120,
  },
  imgpicker: {
    backgroundColor: '#E6E6E6',
    padding: 10,
    width: 180
  },
  img: {
    alignSelf: 'center',
    width: 40,
    height: 40,
    marginVertical: 40
  },
  img2: {
    alignSelf: 'center',
    width: 40,
    height: 40,
    marginVertical: 40
  },
  content_text2: {
    marginTop: 20,
    color: '#929292',
  },
  content_btn: {
    width: 311,
    height: 42,
    backgroundColor: '#1890FF73',
    borderRadius: 6,
    marginTop: 20,
    alignSelf: 'center'
  },
  btn_text: {
    color: '#fff',
    fontSize: 18,
    textAlign: 'center',
    lineHeight: 42
  }
})